package utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

/**
 * Created by fanzhenyu02 on 2020/6/17.
 */
public class JsonUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);

    private static final ObjectMapper objectMapper = new ObjectMapper();


    public static ObjectMapper getObjectMapper() {
        return objectMapper;
    }

    /**
     * Return emtpy String if serializing failed, no exception will be thrown.
     */
    public static String writeValueAsString(Object obj) {
        if (obj == null) {
            return StringUtils.EMPTY;
        }
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (IOException e) {
            LOGGER.warn("{}, {}", e.getMessage(), e);
            return StringUtils.EMPTY;
        }
    }

    /**
     * Return null String if deserialize failed, no exception will be thrown.
     */
    public static <T> T readValue(File file, TypeReference<T> typeReference) {
        if (file == null) {
            return null;
        }
        try {
            return objectMapper.readValue(file, typeReference);
        } catch (IOException e) {
            LOGGER.warn(e.getMessage(), e);
            return null;
        }
    }

    /**
     * Return null String if deserialize failed, no exception will be thrown.
     */
    public static <T> T readValue(String json, TypeReference<T> typeReference) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            return objectMapper.readValue(json, typeReference);
        } catch (IOException e) {
            LOGGER.warn(e.getMessage(), e);
            return null;
        }
    }

    /**
     * Return null String if deserialize failed, no exception will be thrown.
     */
    public static <T> T readValue(String json, Class<T> clazz) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            return objectMapper.readValue(json, clazz);
        } catch (IOException e) {
            LOGGER.warn("{}, {}", e.getMessage(), e);
            return null;
        }
    }

    public static <T> T convertValue(Object object, TypeReference<T> typeReference) {
        if (object == null) {
            return null;
        }
        return objectMapper.convertValue(object, typeReference);
    }
}

